package com.fingard.dsp.bank.directbank.hbc01;

import org.apache.commons.lang.StringUtils;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author XueJy on 2018/9/19.
 * @version 1.0
 */
public class HBC01Base extends DirectBase {
    private Pattern pattern = Pattern.compile("[\\u4E00-\\u9FA5]");
    private SimpleDateFormat sdfdt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss");
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    void writePayCommonHeader(StringBuilder tmpMsg,ReqBatPayRec reqBatPayRec) throws Exception {
        Date now = new Date();
        //IFH,IFILE,CSV,ABC73332001,CNHBAPGCN001561182,3081, 2018/09/03,09:40:47 ,A,1,4,GB01
        String payHead = "IFH,IFILE,CSV,,,,,,A,1.0,,U801";
        String[] headMsgs = payHead.split(",");
        //网银账号 HSBC Connect Id
        headMsgs[3] = getBankConfig().getMapValueByKey("params", "bkPtyId");
        headMsgs[4] = getBankConfig().getMapValueByKey("params", "HSBCnetCustomerID");
//     headMsgs[5] = "PP_" + headMsgs[3] +"_"+ Format.DateTime14Format.format(now);
        headMsgs[5] = reqBatPayRec.reqBatchNO;
        headMsgs[6] = sdf.format(now);
        headMsgs[7] = Format.Time8Format.format(now);
        //支付文件总行数
        headMsgs[10] = String.valueOf(Integer.parseInt(reqBatPayRec.totalNum) + 2);
        for (String headMsg : headMsgs) {
            tmpMsg.append(headMsg).append(",");
        }
        tmpMsg.delete(tmpMsg.length() - 1, tmpMsg.length());
        tmpMsg.append("\r\n");
    }

    void writePayBodyParams(StringBuilder tmpMsg, ReqBatPayRec p_req1988) throws Exception {
        //IFH,IFILE,CSV,ABC73332001,CNHBAPGCN001561182,1210172637474,2018/12/10,17:26:38,A,1.0,3,U801
        //BATHDR,LTR,1,,,,,,,@1ST@,20181210,511055915020,CNY,1128.00,,,,,CNY,,中德安联人寿保险有限公,,,,,,1210172637474,,
        //SECPTY,1001190729014074724,中国工商银行上海市分行,,,,,1128.00,,,托管专户,,,,N,N,,,,,,@HVP@,,,,,,,,,,,,,,,中国工商银行上海市分行,第二营业部,,,,CN,,,,,,OUR,,,,,,,,,,,,,,,,,/CNAPS,,,,,
        //BATHDR,LTR,1,,,,,,,@1ST@,20181210,511055915020,CNY,1128.00,,,,,CNY,,中德安联人寿保险有限公,,,,,,1210172637474,,
        //SECPTY,1001190729014074724,中国工商银行上海市分行,,,,,1128.00,,,托管专户,,,,N,N,,,,,,@HVP@,,,,,,,,,,,,,,,中国工商银行上海市分行,第二营业部,,,,CN,,,,,,OUR,,,,,,,,,,,,,,,,,/CNAPS,,,,,
        //BATHDR,LTR……
        //SECPTY,100……
        String paybody = "BATHDR,LTR,,,,,,,,@1ST@,,,,,,,,,,,,,,,,,,,N";
        String[] tmpPayMsg = paybody.split(",");
        // 数量?
        tmpPayMsg[2] = "1";
        tmpPayMsg[10] = Format.Date8Format.format(new Date());
        tmpPayMsg[11] = p_req1988.ownAct;
        tmpPayMsg[12] = convertCurToBank(p_req1988.ownCur);
        tmpPayMsg[18] = convertCurToBank(p_req1988.ownCur);
        String ownActEnName = getBankConfig().getMapValueByKey("OwnActEnName", p_req1988.ownAct);
        if (ownActEnName != null && !"".equals(ownActEnName)) {
            p_req1988.ownActName = ownActEnName;
        }
        Matcher matcher = pattern.matcher(p_req1988.ownActName);
        if (matcher.find()) {
            if (p_req1988.ownActName.length() > 11) {
                p_req1988.ownActName = p_req1988.ownActName.substring(0, 11);
            }
        } else {
            if (p_req1988.ownActName.length() > 35) {
                p_req1988.ownActName = p_req1988.ownActName.substring(0, 35);
            }
        }
        tmpPayMsg[20] = p_req1988.ownActName;
        while (p_req1988.readRecord()) {
            ReqPayRecDetail detail = p_req1988.readedDetail;
            tmpPayMsg[13] = detail.payAmount;
            tmpPayMsg[26] = detail.askNumber;
            for (String headMsg : tmpPayMsg) {
                tmpMsg.append(headMsg).append(",");
            }
            tmpMsg.delete(tmpMsg.length() - 2, tmpMsg.length());
            tmpMsg.append("\r\n");
            String recbody = "SECPTY,,,,,,,,,,,,,,N,N,,,,,,@HVP@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/CNAPS,,,,,N";
//            recbody = "SECPTY,3248579231234239847,北京戈雅文化传播有限公,,,,,2550.00,,,司,,,,N,N,,,,,,@HVP@,,,,,,,,,,,,,,,中国工商银行股份有限公,司广东省广州天河路支行,,,,CN,,Test123,,,,OUR,,,,,,,,,,,,,,,,,/CNAPS,,,,,"
            String[] tmpRecMsg = recbody.split(",");
            tmpRecMsg[1] = detail.recAct;
            matcher = pattern.matcher(detail.recName);
            if (matcher.find()) {
                if (detail.recName.length() > 30) {
                    tmpRecMsg[2] = detail.recName.substring(0, 11);
                    tmpRecMsg[10] = detail.recName.substring(11, 22);
                    tmpRecMsg[11] = detail.recName.substring(22, 30);
                } else if (detail.recName.length() > 22) {
                    tmpRecMsg[2] = detail.recName.substring(0, 11);
                    tmpRecMsg[10] = detail.recName.substring(11, 22);
                    tmpRecMsg[11] = detail.recName.substring(22);
                } else if (detail.recName.length() > 11) {
                    tmpRecMsg[2] = detail.recName.substring(0, 11);
                    tmpRecMsg[10] = detail.recName.substring(11);
                } else {
                    tmpRecMsg[2] = detail.recName;
                }
            } else {
                if (detail.recName.length() > 35) {
                    detail.recName = detail.recName.substring(0, 35);
                }
            }
//            tmpRecMsg[3] = detail.askNumber;
            tmpRecMsg[7] = detail.payAmount;
//         tmpRecMsg[11] = detail.purpose;
//         tmpRecMsg[12] = detail.recBankName;
            matcher = pattern.matcher(detail.cnapsName);
            if (matcher.find()) {
                if (detail.cnapsName.length() > 22) {
                    tmpRecMsg[36] = detail.cnapsName.substring(0, 11);
                    tmpRecMsg[37] = detail.cnapsName.substring(11, 22);
                } else if (detail.cnapsName.length() > 11) {
                    tmpRecMsg[36] = detail.cnapsName.substring(0, 11);
                    tmpRecMsg[37] = detail.cnapsName.substring(11);
                } else {
                    tmpRecMsg[36] = detail.cnapsName;
                }
            } else {
                if (p_req1988.ownActName.length() > 35) {
                    p_req1988.ownActName = p_req1988.ownActName.substring(0, 35);
                }
            }
            tmpRecMsg[41] = "CN";
            //44-47 交易附言
            String usage = detail.abstractATS + "+" + detail.purpose;
            matcher = pattern.matcher(usage);
            if (matcher.find()) {
                //中文
                if (usage.length() <= 11) {
                    tmpRecMsg[43] = usage;
                } else if (usage.length() <= 22) {
                    tmpRecMsg[43] = usage.substring(0, 11);
                    tmpRecMsg[44] = usage.substring(11);
                } else if (usage.length() <= 33)  {
                    tmpRecMsg[43] = usage.substring(0, 11);
                    tmpRecMsg[44] = usage.substring(11, 22);
                    tmpRecMsg[45] = usage.substring(22);
                } else if (usage.length() <= 44) {
                    tmpRecMsg[43] = usage.substring(0, 11);
                    tmpRecMsg[44] = usage.substring(11, 22);
                    tmpRecMsg[45] = usage.substring(22, 33);
                    tmpRecMsg[46] = usage.substring(33);
                } else {
                    tmpRecMsg[43] = usage.substring(0, 11);
                    tmpRecMsg[44] = usage.substring(11, 22);
                    tmpRecMsg[45] = usage.substring(22, 33);
                    tmpRecMsg[46] = usage.substring(33,44);
                }
            } else {
                //英文
                if (usage.length() <= 30) {
                    tmpRecMsg[43] = usage;
                } else if (usage.length() <= 60) {
                    tmpRecMsg[43] = usage.substring(0, 30);
                    tmpRecMsg[44] = usage.substring(30);
                } else if (usage.length() <= 90)  {
                    tmpRecMsg[43] = usage.substring(0, 30);
                    tmpRecMsg[44] = usage.substring(30, 60);
                    tmpRecMsg[45] = usage.substring(60);
                } else if (usage.length() <= 120) {
                    tmpRecMsg[43] = usage.substring(0, 30);
                    tmpRecMsg[44] = usage.substring(30, 60);
                    tmpRecMsg[45] = usage.substring(60, 90);
                    tmpRecMsg[46] = usage.substring(90);
                } else {
                    tmpRecMsg[43] = usage.substring(0, 30);
                    tmpRecMsg[44] = usage.substring(30, 60);
                    tmpRecMsg[45] = usage.substring(60, 90);
                    tmpRecMsg[46] = usage.substring(90,120);
                }
            }
            tmpRecMsg[47] = "OUR";
            for (String recMsg : tmpRecMsg) {
                tmpMsg.append(recMsg).append(",");
            }

            tmpMsg.delete(tmpMsg.length() - 2, tmpMsg.length());
            tmpMsg.append("\r\n");
        }

        tmpMsg.delete(tmpMsg.length() - 2, tmpMsg.length());
    }



//    FtpReceiver downloadFromFtp(String way) throws IOException {
//        FtpSet ftpSet = bankFront.getFtpSet("LOCAL");
//        ftpSet.downDir = ftpSet.getDownDir("batPay");
//        if ("9188".equals(way)) {
//            ftpSet.downDir = ftpSet.getDownDir("batRec");
//        }
//        FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
//        WriteBankLogLn2("FTP服务器文件下载路径:" + ftpSet.downDir);
//        ftpPortClient.list(ftpSet.downDir);
//        String dataFileDirectory = getCommonDataFileDirectory(new Date(),"HSHBC");
//        //下载失败结果文件
//        FtpReceiver ftpReceiver = new FtpReceiver();
//        for (String filePath : ftpPortClient.arFiles) {
//            ftpReceiver = ftpPortClient.downloadFile(filePath, dataFileDirectory + filePath);
//            if (!ftpReceiver.isCompleted || ConnState.FAIL.equals(ftpReceiver.connState)) {
//                break;
//            }
//        }
//        return ftpReceiver;
//    }
//

    String getTrimPath(String p_path) {
        return StringHelper.trimEnd(p_path, File.separator);
    }

    //获取文件夹目录下所有文件名
    List<String> getDirectoryAllFileName(String balanceFilePath) {
        List<String> fileNames = new ArrayList<String>();
        File file = new File(balanceFilePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                fileNames.add(files[i].getName());
            }
        }
        return fileNames;
    }

    String convertCommaToPoint(String amount) {
        if (!StringUtils.isEmpty(amount)) {
            if (amount.indexOf('.') > -1) {
                //Do nothing
            } else if (amount.indexOf(',') > -1) {
                if (amount.indexOf(',') - amount.lastIndexOf(',') == 0) {
                    amount = amount.replace(',', '.');
                }
            }
        }
        return amount;
    }

    FtpReceiver sendToBank(String fullFilePath, String fileName) throws IOException {
        FtpSet ftpSet = bankFront.getFtpSet("sftpserver");
        SftpPortClient sftpPortClient = null;
        sftpPortClient = new SftpPortClient(ftpSet);
        WriteBankLogLn("本地文件路径:" + fullFilePath);
        WriteBankLogLn("SFTP服务器文件路径:" + ftpSet.upDir);
        WriteBankLogLn2("SFTP服务器文件上传地址:" + ftpSet.serverIP + ":" + ftpSet.port);
        FtpReceiver ftpReceiver= sftpPortClient.uploadFile("", fullFilePath, fileName);
        return ftpReceiver;
    }



}
